package com.sun.javafx.fxml;

import javafx.application.Platform;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.ObservableSet;
import javafx.collections.SetChangeListener;

import java.util.Collection;
import java.util.List;
import java.util.function.Function;

public class ObservableLists {
    public static void bindBidirectional(ObservableList<String> list, ObservableSet<String> src) {
        syncList(list,src);
        syncList(src,list);

        list.addListener((ListChangeListener<String>) change -> {
            if(change.next()){
                syncList(src,list);
            }
        });


        src.addListener((SetChangeListener<String>) change -> syncList(list,src));
    }
        public static void bindBidirectional(ObservableList<String> list, ObservableList<String> src) {
        syncList(list,src);
        syncList(src,list);

        list.addListener((ListChangeListener<String>) change -> {
            while (change.next()){
                if (change.wasAdded()) {
                    List<? extends String> addedSubList = change.getAddedSubList();

                }
            }
        });

        src.addListener((ListChangeListener<String>) change -> {
            if(change.next()){
                Platform.runLater(() ->  syncList(list,src));
            }
        });
    }

    private static void syncList(Collection<String> list, Collection<String> src){
        //list.clear();
        list.addAll(src);
    }

    public static  <D,T> void bindBidirectional(ObservableList<D> list, ObservableList<T> src, Function<D,T> fun) {
        list.addListener(new ListChangeListener<D>() {
            @Override
            public void onChanged(Change<? extends D> change) {

            }
        });
    }
}
